<template>
  <div class="machine-history">
    <div class="page-title">子页表1—机台历史累计数据</div>
    
    <!-- 筛选表单 -->
    <div class="filter-row" style="margin-bottom: 20px;">
      <el-form :inline="true" :model="filterForm" size="small">
        <el-form-item label="渠道">
          <el-select v-model="filterForm.channel" placeholder="请选择渠道" style="width: 150px;" clearable>
            <el-option
              v-for="item in channelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>机台历史累计数据</span>
        <el-button 
          type="success" 
          size="small" 
          icon="el-icon-download"
          style="float: right;"
          @click="exportData"
          :loading="exportLoading">
          导出CSV
        </el-button>
      </div>

      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :span-method="objectSpanMethod"
        :header-cell-style="headerCellStyle"
        :cell-style="cellStyle"
        v-loading="loading"
      >
        <!-- 截至目前列 -->
        <el-table-column prop="status" width="100" align="center">
          <template slot="header">
            <div class="header-cell"></div>
          </template>
          <template slot-scope="scope">
            <span v-if="scope.$index === 0" class="status-text">截至目前</span>
          </template>
        </el-table-column>
        
        <!-- 游戏列 -->
        <el-table-column label="游戏" align="center">
          <template slot="header">
            <div class="header-cell">游戏</div>
          </template>
          <template slot-scope="scope">
            {{ scope.row.game_name }}
          </template>
        </el-table-column>
        
        <!-- 机台 -->
        <el-table-column label="机台" align="center">
          <el-table-column prop="total_play" label="总存金币" align="center" width="100"></el-table-column>
          <el-table-column prop="total_win" label="总赢金币" align="center" width="100"></el-table-column>
          <el-table-column prop="total_diff" label="总存-总赢" align="center" width="100"></el-table-column>
          <el-table-column prop="total_rtp" label="总RTP" align="center" width="100">
            <template slot-scope="scope">
              {{ scope.row.total_rtp !== null && scope.row.total_rtp !== undefined && scope.row.total_rtp !== '' ? scope.row.total_rtp + '%' : '--' }}
            </template>
          </el-table-column>
        </el-table-column>
        
        <!-- 普通模式 -->
        <el-table-column label="普通模式" align="center">
          <el-table-column prop="total_play_normal" label="总存金币" align="center" width="100"></el-table-column>
          <el-table-column prop="total_win_normal" label="总赢金币" align="center" width="100"></el-table-column>
          <el-table-column prop="total_rtp_normal" label="总RTP" align="center" width="100">
            <template slot-scope="scope">
              {{ scope.row.total_rtp_normal !== null && scope.row.total_rtp_normal !== undefined && scope.row.total_rtp_normal !== '' ? scope.row.total_rtp_normal + '%' : '--' }}
            </template>
          </el-table-column>
          <el-table-column label="免费模式总金币" align="center" width="130">
            <template slot-scope="scope">
              --
            </template>
          </el-table-column>
        </el-table-column>
        
        <!-- BELL模式 -->
        <el-table-column label="BELL模式" align="center">
          <el-table-column prop="total_play_beli" label="总存金币" align="center" width="100"></el-table-column>
          <el-table-column prop="total_win_beli" label="总赢金币" align="center" width="100"></el-table-column>
          <el-table-column prop="total_rtp_beli" label="总RTP" align="center" width="100">
            <template slot-scope="scope">
              {{ scope.row.total_rtp_beli !== null && scope.row.total_rtp_beli !== undefined && scope.row.total_rtp_beli !== '' ? scope.row.total_rtp_beli + '%' : '--' }}
            </template>
          </el-table-column>
        </el-table-column>
        
        <!-- 超级BELL模式 -->
        <el-table-column label="超级BELL模式" align="center">
          <el-table-column prop="total_play_super" label="总存金币" align="center" width="100"></el-table-column>
          <el-table-column prop="total_win_super" label="总赢金币" align="center" width="100"></el-table-column>
          <el-table-column prop="total_rtp_super" label="总RTP" align="center" width="100">
            <template slot-scope="scope">
              {{ scope.row.total_rtp_super !== null && scope.row.total_rtp_super !== undefined && scope.row.total_rtp_super !== '' ? scope.row.total_rtp_super + '%' : '--' }}
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { gameTotalList } from '@/api/user'
import { exportDataToCsv } from '@/utils/export'
import channelMixin from '@/mixins/channelMixin'

export default {
  name: 'MachineHistory',
  mixins: [channelMixin],
  data() {
    return {
      tableData: [],
      loading: false,
      filterForm: {
        channel: null,
        user_tag: 0,
        game_id: 0,
        begin_time: '',
        end_time: '',
        page: 1,
        page_size: 100
      },
      exportLoading: false
    };
  },
  created() {
    // 渠道选项通过mixin自动加载
    this.fetchData();
  },
  methods: {
    async fetchData() {
      this.loading = true;
      try {
        const params = {
          channel: this.formatChannelParam(this.filterForm.channel),
          user_tag: 0,
          game_id: 0,
          begin_time: '',
          end_time: '',
          page: 1,
          page_size: 100
        }
        
        console.log('===== MachineHistory Debug Info =====')
        console.log('发送参数:', params)
        
        const response = await gameTotalList(params)
        console.log('接口返回完整数据:', response)
        
        if (response && response.code === 0) {
          console.log('接口成功，response.data:', response.data)
          console.log('response.data的类型:', typeof response.data)
          console.log('response.data的结构:', Object.keys(response.data || {}))
          
          // 根据接口文档，gameTotalList返回game_totals数组
          let records = []
          if (response.data && response.data.game_totals && Array.isArray(response.data.game_totals)) {
            records = response.data.game_totals
            console.log('使用 response.data.game_totals')
          } else if (response.data && response.data.records && Array.isArray(response.data.records)) {
            records = response.data.records
            console.log('使用 response.data.records')
          } else if (response.data && response.data.list && Array.isArray(response.data.list)) {
            records = response.data.list
            console.log('使用 response.data.list')
          } else if (Array.isArray(response.data)) {
            records = response.data
            console.log('使用 response.data 直接数组')
          } else if (response.data && response.data.data && Array.isArray(response.data.data)) {
            records = response.data.data
            console.log('使用 response.data.data')
          } else {
            console.log('未找到数组数据，尝试遍历所有属性:')
            if (response.data && typeof response.data === 'object') {
              for (let key in response.data) {
                console.log(`response.data.${key}:`, response.data[key], 'isArray:', Array.isArray(response.data[key]))
                if (Array.isArray(response.data[key])) {
                  records = response.data[key]
                  console.log(`找到数组数据在 response.data.${key}`)
                  break
                }
              }
            }
          }
          
          console.log('解析后的records:', records)
          console.log('records长度:', records.length)
          console.log('records第一条数据:', records[0])
          
          // 强制设置数据并触发视图更新
          this.tableData = [...records]
          
          console.log('设置tableData长度:', this.tableData.length)
          console.log('当前tableData:', this.tableData)
          
          // 强制Vue重新渲染
          this.$nextTick(() => {
            this.$forceUpdate()
            console.log('强制更新完成，当前tableData:', this.tableData)
          })
          
        } else {
          console.error('接口返回错误:', response)
          this.$message.error(response.msg || response.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取机台历史数据失败:', error)
        this.$message.error('获取数据失败: ' + error.message)
      } finally {
        this.loading = false;
      }
    },
    formatRTP(rtp) {
      if (rtp === null || rtp === undefined || rtp === '') return '--'
      return typeof rtp === 'number' ? `${(rtp * 100).toFixed(2)}%` : rtp
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 合并第一列所有行
      if (columnIndex === 0) {
        if (rowIndex === 0) {
          return {
            rowspan: this.tableData.length,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    headerCellStyle() {
      return {
        backgroundColor: '#e6f1fc',
        color: '#333',
        fontWeight: '600',
        padding: '8px',
        textAlign: 'center'
      };
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 && rowIndex === 0) {
        return {
          padding: '0',
          fontSize: '14px',
          color: '#333',
          fontWeight: '500',
          height: '100%'
        };
      }
      return {
        padding: '5px',
        fontSize: '14px'
      };
    },
    handleSearch() {
      this.fetchData()
    },
    resetFilter() {
      this.filterForm.channel = null
      this.fetchData()
    },
    async exportData() {
      this.exportLoading = true
      try {
        const params = {
          channel: this.formatChannelParam(this.filterForm.channel),
          page: 1,
          page_size: 10000
        }
        
        const response = await gameTotalList(params)
        const allData = response.data.game_totals || []
        
        const columns = [
          { prop: 'Id', label: '序号' },
          { prop: 'channel', label: '渠道' },
          { prop: 'game_id', label: '游戏ID' },
          { prop: 'game_name', label: '游戏名称' },
          { prop: 'total_play', label: '总玩金币' },
          { prop: 'total_win', label: '总赢金币' },
          { prop: 'total_diff', label: '总玩-总赢' },
          { prop: 'total_rtp', label: '总RTP' }
        ]
        
        const now = new Date()
        const dateStr = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0')
        
        const fileName = `机台历史累计数据_${dateStr}.csv`
        exportDataToCsv(allData, columns, fileName)
        this.$message.success('导出成功！')
      } catch (error) {
        this.$message.error('导出失败')
        console.error(error)
      } finally {
        this.exportLoading = false
      }
    }
  }
};
</script>

<style scoped>
.machine-history {
  width: 100%;
}

.page-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
  display: none; /* 隐藏标题，由于表格上方有标题 */
}

.header-cell {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.status-text {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  position: absolute;
  top: 0;
  left: 0;
  font-weight: 500;
}

::v-deep .el-table th {
  background-color: #e6f1fc;
  padding: 8px 0;
}

::v-deep .el-table td {
  padding: 8px 0;
}

::v-deep .el-table__row td:first-child {
  position: relative;
}

::v-deep .el-table .cell {
  word-break: normal;
  white-space: nowrap;
}

::v-deep .el-table--border th, 
::v-deep .el-table--border td {
  border-right: 1px solid #dcdfe6;
}

/* 确保第一列的单元格可以正确容纳合并后的内容 */
::v-deep .el-table__row:first-child td:first-child {
  vertical-align: middle;
  position: relative;
}

/* 移除多余的伪元素样式 */
::v-deep .el-table__row td:first-child:after {
  content: none;
}

::v-deep .el-table__row:not(:first-child) td:first-child:after {
  content: none;
}
</style> 